package org.genuflex.vo
{
	import com.adobe.cairngorm.vo.IValueObject;
	import org.genuflex.utils.GenuflexDataCache;
	import flash.utils.getQualifiedClassName;
	import flash.utils.getDefinitionByName;
	import org.genuflex.utils.GenuflexDataFunctions;
	
	public class GenuflexValueObject implements IValueObject
	{
		public function getLabel() : String {
			return "";
		}
		/*
		 * labelOf
		 * A null-safe (and cleaner code) way of getting the label from a GenuflexValue Object
		 */
		public function labelOf(fieldName : String) : String {
			//If object is a string, try to read the value off of this object
			// if null, look for a belongsTo association
			if (GenuflexDataFunctions.isNotEmpty(fieldName)) {
				
				if (this[fieldName] == null) {
					var destClass : Class = getDefinitionByName(getQualifiedClassName(this)) as Class;
					var dataCache : GenuflexDataCache =  GenuflexDataCache.getInstance();
					var belongsTo : BelongsToAssociation =dataCache.getBelongsToByDestination(destClass, fieldName);
					
					if (belongsTo != null && dataCache.managedClasses.contains(belongsTo.destClass)) {
						this[fieldName] = dataCache.getData(belongsTo.destClass, this[belongsTo.foreignKeyName]);
					}
				}
				
				return this[fieldName] != null ? this[fieldName].getLabel() : '';				
			}
			else {
				return "Bad labelOf param";
			}
						 
		}		
		
		public function toString():String {
			return getLabel();
		}
		
		public function toSearchableString():String {
			return toString();
		}
	}
}